package com.pet.platform.controller.admin;

import com.pet.platform.common.PageResult;
import com.pet.platform.common.Result;
import com.pet.platform.dto.UserDTO;
import com.pet.platform.dto.UserQueryDTO;
import com.pet.platform.entity.User;
import com.pet.platform.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 管理员用户控制器
 */
@RestController
@RequestMapping("/api/admin/users")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class AdminUserController {
    
    private final UserService userService;
    
    /**
     * 获取用户列表
     */
    @GetMapping
    public Result<PageResult<UserDTO>> getUserList(UserQueryDTO queryDTO) {
        return Result.success(userService.findPage(queryDTO));
    }
    
    /**
     * 获取用户详情
     */
    @GetMapping("/{id}")
    public Result<User> getUserDetail(@PathVariable Long id) {
        return Result.success(userService.findById(id));
    }
    
    /**
     * 创建用户
     */
    @PostMapping
    public Result<Void> createUser(@Valid @RequestBody UserDTO userDTO) {
        // 检查用户名是否已存在
        User existingUser = userService.findByUsername(userDTO.getUsername());
        if (existingUser != null) {
            return Result.error("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        UserQueryDTO queryDTO = new UserQueryDTO();
        queryDTO.setEmail(userDTO.getEmail());
        PageResult<UserDTO> result = userService.findPage(queryDTO);
        if (result.getTotal() > 0) {
            return Result.error("邮箱已被使用");
        }

        userService.create(userDTO);
        return Result.success();
    }
    
    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    public Result<Void> updateUser(@PathVariable Long id, @Valid @RequestBody UserDTO userDTO) {
        userService.update(id, userDTO);
        return Result.success();
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        userService.delete(id);
        return Result.success();
    }
    
    /**
     * 更新用户状态
     */
    @PutMapping("/{id}/status")
    public Result<Void> updateUserStatus(@PathVariable Long id, @RequestParam Integer status) {
        userService.updateStatus(id, status);
        return Result.success();
    }
} 